<template>
  <div>
    <div class="header" :style="{ backgroundColor: getHeaderBackgroundColor() }">
      <van-icon name="arrow-left" size="20px" @click="goBack" style="margin-top: -191px" />
      <div class="header-content">
        <h2 style="font-size: 50px; color: white">{{weightData.weight}} Kg</h2>
        <p style="color: white">BMI {{weightData.bmi}} 标准</p>
        <button @click="showWeightModal = true" style="width: 147px; height: 50px; background-color: #FDDB78; border-radius: 40px; border: none; color: white; font-weight: 900">记录体重</button>
      </div>
      <div class="current-time" style="color: white">{{currentTime}}</div>
    </div>
    <!-- 外部盒子 -->
    <div class="chart-box">
      <h2>体重趋势 <span style="font-size:14px;color:gray">(单位：Kg)</span></h2>
      <div class="chart-container">
        <canvas id="weightChart" width="400" height="250"></canvas>
      </div>
    </div>
    <div style="font-size: 23px;
    height: 45px;
    margin-left: 32px;">体重记录</div>
    <ul class="weight-records-list">
      <li v-for="(record, index) in weightRecords" :key="index" class="weight-record-item">
        <div class="record-date">{{formatDate(record.recordTime)}}</div>
        <div class="record-weight">{{record.weight}} Kg</div>
        <span v-if="record.status === 'normal'" class="status-normal">正常</span>
        <span v-if="record.status === 'abnormal'" class="status-abnormal">异常</span>
        <div class="record-actions">
          <button @click="editRecord(index)" class="edit-button"><van-icon name="edit" size="16px" /></button>
          <button @click="deleteRecord(index)" class="delete-button"><van-icon name="delete" size="16px" /></button>
        </div>
      </li>
    </ul>
    <!-- 弹出层组件 -->
    <div v-if="showWeightModal" class="weight-modal">
      <div class="modal-content">
        <h5 class="modal-title">体重记录</h5>
        <div class="weight-value-container">
          <h1>{{value}} Kg</h1>
        </div>
        <div class="weight-slider-container">
          <van-slider style="margin-left: 40px" v-model="value" @change="onChange" />
        </div>
        <div class="button-group-container">
          <div class="button-group">
            <button @click="handleCancel" class="cancel-button">取消</button>
            <button @click="confirmWeight" class="confirm-button">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart } from 'chart.js';
import { CategoryScale, LinearScale } from 'chart.js';
import { LineController } from 'chart.js';
import { PointElement, LineElement } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import axios from 'axios';

Chart.register(CategoryScale, LinearScale, LineController, PointElement, LineElement, ChartDataLabels);

export default {
  data() {
    return {
      value: 50,
      weightData: {
        weight: 52.0,
        bmi: 20.7
      },
      weightRecords: [],
      chart: null,
      showWeightModal: false,
      currentTime: '',
      recordData: {} ,// 用于存储要发送到后端的数据
      isEdit: false, // 新增标志位，判断是编辑还是添加
      editRecordId: null // 存储编辑记录的id
    };
  },
  methods: {
    editRecord(index) {
      const record = this.weightRecords[index];
      const { id, weight } = record;
      this.value = weight;
      this.editRecordId = id;
      this.isEdit = true;
      this.showWeightModal = true;
    },
    deleteRecord(index) {
      const record = this.weightRecords[index];
      const { id } = record;
      axios.delete(`http://localhost:10086/api/doctor/health_monitoring_weight/deleteWeightRecord/${id}`, {
        headers: {
          'token': JSON.parse(localStorage.getItem("token"))
        }
      })
          .then(response => {
            console.log('体重记录删除成功', response.data);
            // 从本地数组中删除该记录并更新图表
            this.weightRecords.splice(index, 1);
            this.drawChart();
          })
          .catch(error => {
            console.error('体重记录删除失败', error);
            this.$message.error('体重记录删除失败，请重试');
          });
    },
    findHealthWeight() {
      return this.axios.get(`http://localhost:10086/api/user/user/findHealthWeight`)
          .then(res => {
            this.weightRecords = res.data.data;
            this.weightRecords.forEach(record => {
              record.weight = Number(record.weight);
              let status = 'normal';
              if (record.weight > 65 || record.weight < 40) {
                status = 'abnormal';
              }
              record.status = status;
            });
            this.drawChart();
            return this.weightRecords;
          })
          .catch(error => {
            console.error('获取体重数据失败', error);
            throw error;
          });
    },
    onChange(value) {
      this.$toast('当前值：' + value);
    },
    goBack() {
      this.$router.go(-1);
    },
    drawChart() {
      const ctx = document.getElementById('weightChart').getContext('2d');
      const weightDataPoints = this.weightRecords.map(record => record.weight);
      const labels = this.weightRecords.map(record => this.formatDate(record.recordTime));
      const today = this.formatDate(new Date());
      const pointColors = [];
      const borderColors = [];
      const dataLabelsColors = [];

      for (let i = 0; i < weightDataPoints.length; i++) {
        const recordDate = this.formatDate(this.weightRecords[i].recordTime);
        if (recordDate === today) {
          pointColors.push('white');
          borderColors.push('red');
          dataLabelsColors.push('red');
        } else {
          pointColors.push('white');
          borderColors.push('#007AFF');
          dataLabelsColors.push('#007AFF');
        }
      }

      if (this.chart) {
        this.chart.destroy();
      }

      const minWeight = Math.min(...weightDataPoints);
      const maxWeight = Math.max(...weightDataPoints);
      const yAxisMin = Math.floor(minWeight * 2) / 2 - 1;
      const yAxisMax = Math.ceil(maxWeight * 2) / 2 + 1.5;

      this.chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: '体重趋势 (单位：Kg)',
            data: weightDataPoints,
            borderColor: borderColors,
            backgroundColor: 'rgba(153, 204, 255, 0.2)',
            pointRadius: 4,
            pointBackgroundColor: pointColors,
            pointBorderColor: borderColors,
            pointHoverRadius: 6,
            pointHoverBackgroundColor: pointColors,
            pointHoverBorderColor: borderColors,
            fill: 'origin',
            tension: 0.4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              type: 'category',
              grid: {display: false},
              ticks: {color: '#666', autoSkip: false, maxRotation: 0, padding: 5},
              offset: true
            },
            y: {
              display: true,
              type: 'linear',
              beginAtZero: false,
              grid: {
                display: true,
                color: 'rgba(0, 0, 0, 0.1)',
                lineWidth: 1,
                drawBorder: false,
                zeroLineColor: 'rgba(0, 0, 0, 0.1)',
                zeroLineWidth: 1,
                gridLines: {
                  drawOnChartArea: true,
                  drawTicks: false,
                  min: yAxisMin,
                  max: yAxisMax,
                  stepSize: 0.5
                }
              },
              ticks: {
                display: false,
                min: yAxisMin,
                max: yAxisMax,
                stepSize: 0.5
              }
            }
          },
          plugins: {
            legend: {display: false},
            title: {
              display: true,
              text: '体重趋势 (单位：Kg)',
              font: {size: 16, weight: 'bold', color: '#333'},
              padding: {bottom: 10}
            },
            tooltip: {enabled: false},
            datalabels: {
              anchor: 'end',
              align: 'top',
              color: dataLabelsColors,
              font: {size: 12, weight: 'bold'},
              formatter: (value) => `${value} Kg`,
              display: 'auto',
              offset: 10,
              clamp: true,
              borderWidth: 0,
              borderRadius: 3
            }
          },
          layout: {
            padding: {left: 20, right: 20, top: 30, bottom: 10}
          },
          elements: {
            line: {
              borderWidth: 2,
              borderColor: '#007AFF',
              tension: 0.4
            }
          }
        }
      });
    },
    recordWeight() {
      const newRecord = {
        date: new Date().toLocaleDateString(),
        weight: this.weightData.weight,
        status: 'normal'
      };
      this.weightRecords.push(newRecord);
      this.drawChart();
    },
    confirmWeight() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      let status = 'normal';
      if (this.value > 65 || this.value < 40) {
        status = 'abnormal';
      }
      this.recordData = {
        date: `${year}-${month < 10? '0' : ''}${month}-${day < 10? '0' : ''}${day}`,
        weight: this.value,
        status: status
      };
      if (this.isEdit && this.editRecordId) {
        this.recordData.id = this.editRecordId;
        axios.post('http://localhost:10086/api/doctor/health_monitoring_weight/updateWeightRecord', this.recordData, {
          headers: {
            'token': JSON.parse(localStorage.getItem("token"))
          }
        })
            .then(response => {
              console.log('体重记录修改成功', response.data);
              this.drawChart();
              this.findHealthWeight();
              this.showWeightModal = false;
              this.isEdit = false;
              this.editRecordId = null;
            })
            .catch(error => {
              console.error('体重记录修改失败', error);
              this.$message.error('体重记录修改失败，请重试');
            });
      } else {
        axios.post('http://localhost:10086/api/doctor/health_monitoring_weight/saveWeightRecord', this.recordData, {
          headers: {
            'token': JSON.parse(localStorage.getItem("token"))
          }
        })
            .then(response => {
              console.log('体重记录保存成功', response.data);
              this.drawChart();
              this.findHealthWeight();
              this.showWeightModal = false;
            })
            .catch(error => {
              console.error('体重记录保存失败', error);
              this.$message.error('体重记录保存失败，请重试');
            });
      }
    },
    handleCancel() {
      this.showWeightModal = false;
      // 重置value，确保下次打开时显示初始值
      this.value = 50;
    },
    getHeaderBackgroundColor() {
      return '#4A94F5';
    },
    updateCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      this.currentTime = `${year}-${month}-${day} ${hour}:${minute}`;
    },
    formatDate(date) {
      const d = new Date(date);
      const month = d.getMonth() + 1;
      const day = d.getDate();
      return `${month}/${day}`;
    }
  },
  mounted() {
    this.drawChart();
    this.updateCurrentTime();
    setInterval(() => {
      this.updateCurrentTime();
    }, 60 * 1000);
  },
  async created() {
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({ name: 'login' });
      }, 666);
    }
    this.axios = axios.create();
    this.axios.defaults.headers.common['token'] = token;
    const routeValue = this.$route.params.value;
    if (routeValue!== undefined) {
      this.weightData.weight = parseFloat(routeValue);
    }
    await this.findHealthWeight();
  }
};
</script>

<style scoped>
.header {
  position: relative;
  background-color: #4A94F5;
  padding: 20px;
  text-align: center;
  background-size: cover;
  background-position: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  color: white;
  margin-top: 0; /* 确保顶部外边距为 0 */
}

.header-content {
  margin-left: 105px;
  margin-top: 20px;
  flex-direction: column;
  align-items: center;
}

.current-time {
  position: absolute;
  margin-right: 145px;
  margin-top: 20px;
  top: 10px;
  right: 10px;
  font-size: 14px;
}

.chart-box {
  border: 1px solid #ccc;
  border-radius: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  width: 340px;
}

.chart-container {
  width: 100%;
  height: 250px;
}

.weight-records-list {
  list-style: none;
  padding: 0;
}

.weight-record-item {
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 0px 10px rgba(0, 112, 255, 0.5);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 35px;
  width: 76%;
}

.record-date {
  color: #666;
  font-size: 14px;
}

.record-weight {
  font-size: 18px;
  font-weight: bold;
}

.status-normal {
  background-color: #c8e6c9;
  color: #43a047;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
}

.status-abnormal {
  background-color: #ef9a9a;
  color: #e53935;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
}

.record-actions {
  display: flex;
  align-items: center;
}

.edit-button,
.delete-button {
  background: none;
  border: none;
  margin-left: 10px;
  cursor: pointer;
}

.weight-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 300px;
  background-color: white;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
  animation: slide-up 0.3s ease;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modal-content {
  width: 100%;
  padding: 20px;
  text-align: center;
}

.modal-title {
  margin: 0;
  margin-bottom: 10px;
  text-align: center;
}

.weight-value-container {
  width: 100%;
  text-align: center;
}

.weight-slider-container {
  width: 80%;
  margin-bottom: 20px;
}

.button-group-container {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
  box-sizing: border-box;
}

.button-group {
  display: flex;
}

.cancel-button {
  padding: 10px 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: white;
  color: #007AFF;
  font-weight: bold;
  margin-right: 10px;
}

.confirm-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007AFF;
  color: white;
  font-weight: bold;
}
</style>